﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;

namespace LockCrypt.Core {
    public static class ByteConversion {

        /// <summary>
        /// Converts a byte array to an object.
        /// </summary>
        /// <typeparam name="T">The type of the object</typeparam>
        /// <param name="rawValue">The raw value.</param>
        /// <returns>The array as an object of the specified type</returns>
        public static T FromByteArray<T>(byte[] rawValue) {
            if(typeof(T) == typeof(string)) {
                return (T)Convert.ChangeType(Encoding.UTF8.GetString(rawValue), typeof(string));
            } else if(typeof(T) == typeof(int)) {
                return (T)Convert.ChangeType(rawValue, typeof(int));
            }
            MemoryStream memStream = new MemoryStream();
            BinaryFormatter binForm = new BinaryFormatter();
            memStream.Write(rawValue, 0, rawValue.Length);
            memStream.Seek(0, SeekOrigin.Begin);
            T obj = (T)binForm.Deserialize(memStream);
            return obj;
        }

        /// <summary>
        /// Converts an arbitrary type to a byte array.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <returns>The object as a byte[]</returns>
        public static byte[] ToByteArray(object value) {
            if(value == null)
                return null;
            else if(value is string || value is int)
                return Encoding.UTF8.GetBytes(value.ToString());
            BinaryFormatter bf = new BinaryFormatter();
            MemoryStream ms = new MemoryStream();
            bf.Serialize(ms, value);
            return ms.ToArray();
        }
    }
}
